package no.nordicsemi.demo.slice;

import no.nordicsemi.demo.HistoryItemProvider;
import no.nordicsemi.demo.ResourceTable;
import no.nordicsemi.support.v18.scanner.*;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.bluetooth.ble.BleScanFilter;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.*;

public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private Button btnStartScan, btnStopScan;
    private RadioButton one, two, three, four;
    private RadioContainer rabut;
    private BluetoothLeScannerCompat scanner;

    private List<ScanResult> beans = new ArrayList<>();
    Context context;
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");
    //设置蓝牙扫描过滤器集合
    private List<ScanFilter> scanFilterList;
    //设置蓝牙扫描过滤器
    private ScanFilter.Builder scanFilterBuilder;
    //设置蓝牙扫描设置
    private ScanSettings.Builder scanSettingBuilder;
    private ListContainer dialog;
    private HistoryItemProvider historyItemProvider;
    private boolean isBut = false;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
        initClick();
        String[] permission = {"ohos.permission.LOCATION", "ohos.permission.USE_BLUETOOTH"
                , "ohos.permission.DISCOVER_BLUETOOTH", "ohos.permission.LOCATION_IN_BACKGROUND"
                , "ohos.permission.GET_NETWORK_INFO"};
        requestPermissionsFromUser(permission, 0);
        return;
    }

    private void initView() {
        dialog = (ListContainer) findComponentById(ResourceTable.Id_dialog);
        btnStartScan = (Button) findComponentById(ResourceTable.Id_btn_start_scan);
        btnStopScan = (Button) findComponentById(ResourceTable.Id_btn_stop_scan);
        one = (RadioButton) findComponentById(ResourceTable.Id_one);
        two = (RadioButton) findComponentById(ResourceTable.Id_two);
        three = (RadioButton) findComponentById(ResourceTable.Id_three);
        four = (RadioButton) findComponentById(ResourceTable.Id_four);
        rabut = (RadioContainer) findComponentById(ResourceTable.Id_rabut);
        scanner = BluetoothLeScannerCompat.getScanner();
        historyItemProvider = new HistoryItemProvider(beans, MainAbilitySlice.this, ResourceTable.Layout_item_layout);
        dialog.setItemProvider(historyItemProvider);
        rabut.mark(0);
    }

    private void initClick() {
        btnStartScan.setClickedListener(this);
        btnStopScan.setClickedListener(this);
        rabut.setMarkChangedListener(new RadioContainer.CheckedStateChangedListener() {
            @Override
            public void onCheckedChanged(RadioContainer radioContainer, int i) {
                if (i == 0) {
                    if (!isBut) {
                        ScanSettings settings = new ScanSettings.Builder()
                                .setLegacy(false)
                                .setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
                                .setReportDelay(10000)
                                .setUseHardwareBatchingIfSupported(false)
                                .build();
                    } else {
                        new ToastDialog(getContext())
                                .setText("搜索中,请结束当前搜索")
                                .show();
                    }
                } else if (i == 1) {
                    if (!isBut) {
                        ScanSettings settings = new ScanSettings.Builder()
                                .setLegacy(false)
                                .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                                .setReportDelay(10000)
                                .setUseHardwareBatchingIfSupported(false)
                                .build();
                    } else {
                        new ToastDialog(getContext())
                                .setText("搜索中,请结束当前搜索")
                                .show();
                    }
                } else if (i == 2) {
                    if (!isBut) {
                        ScanSettings settings = new ScanSettings.Builder()
                                .setLegacy(false)
                                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                                .setReportDelay(10000)
                                .setUseHardwareBatchingIfSupported(false)
                                .build();
                    } else {
                        new ToastDialog(getContext())
                                .setText("搜索中,请结束当前搜索")
                                .show();
                    }
                } else {
                    if (!isBut) {
                        ScanSettings settings = new ScanSettings.Builder()
                                .setLegacy(false)
                                .setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC)
                                .setReportDelay(10000)
                                .setUseHardwareBatchingIfSupported(false)
                                .build();
                    } else {
                        new ToastDialog(getContext())
                                .setText("搜索中,请结束当前搜索")
                                .show();
                    }
                }
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private ScanSettings buildScanSettings() {
        scanSettingBuilder = new ScanSettings.Builder();
        scanSettingBuilder.setUseHardwareBatchingIfSupported(false);
        //设置蓝牙LE扫描的扫描模式。
        //使用最高占空比进行扫描。建议只在应用程序处于此模式时使用此模式在前台运行
        scanSettingBuilder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY);
        //设置蓝牙LE扫描滤波器硬件匹配的匹配模式
        //在主动模式下，即使信号强度较弱，hw也会更快地确定匹配.在一段时间内很少有目击/匹配。
        scanSettingBuilder.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE);
        //设置蓝牙LE扫描的回调类型
        //为每一个匹配过滤条件的蓝牙广告触发一个回调。如果没有过滤器是活动的，所有的广告包被报告
        scanSettingBuilder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
        scanSettingBuilder.setReportDelay(10000);
        scanSettingBuilder.setUseHardwareBatchingIfSupported(false);
        return scanSettingBuilder.build();
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_btn_start_scan:
                if (!isBut) {
                    start();
                    new ToastDialog(getContext())
                            .setText("开始")
                            .show();
                } else {
                    new ToastDialog(getContext())
                            .setText("搜索中")
                            .show();
                }
                break;
            case ResourceTable.Id_btn_stop_scan:
                if (isBut) {
                    stop();
                    new ToastDialog(getContext())
                            .setText("结束")
                            .show();
                } else {
                    new ToastDialog(getContext())
                            .setText("已结束")
                            .show();
                }
                break;
        }
    }

    private void start() {
        isBut = true;
        List<BleScanFilter> filters = new ArrayList<>();
        scanner.startScan(this, null, buildScanSettings(), scanCallback);
        scanner.startScan(filters, buildScanSettings(), this, null);
    }

    private void stop() {
        isBut = false;
        scanner.stopScan(scanCallback);
        beans.clear();
        getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                historyItemProvider.notifyDataChanged();
            }
        });
    }

    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            System.out.println("LOGLIST" + "/**/" + "RESULTDEVICE-------------------------------" + result.getDevice());
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
            if (results.size() > 0) {
                beans.clear();
                beans.addAll(results);
            }

            getUITaskDispatcher().asyncDispatch(new Runnable() {
                @Override
                public void run() {
                    historyItemProvider.notifyDataChanged();
                }
            });
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            System.out.println("onScanFailed");
        }
    };

    @Override
    protected void onBackground() {
        super.onBackground();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}